import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

maintain_type_router = APIRouter(prefix="/maintain/maintainType", tags=["保养类型管理"],
                                 dependencies=[Depends(oauth2_scheme)])


class MaintainTypeSearch(PaginationBase):
    fmmtypename: str = Field("", description="保养类型名")


@maintain_type_router.get("/list", summary="保养类型查询接口")
def list_maintain_type(search: MaintainTypeSearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from s_ts_maintain_type where 1=1"
    if search.fmmtypename != "":
        sql = sql + " and fmmtypename like concat('%', :fmmtypename ,'%')"
        param["fmmtypename"] = search.fmmtypename
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fmmtypeno,fmmtypename,fmemo,fupddate,foperator"
    sql = sql + " from s_ts_maintain_type where 1=1"
    if search.fmmtypename != "":
        sql = sql + " and fmmtypename like concat('%', :fmmtypename ,'%')"
        param["fmmtypename"] = search.fmmtypename
    if search.order == "desc":
        sql = sql + " order by  fmmtypeno desc "
    else:
        sql = sql + " order by  fmmtypeno "
    sql = sql + " limit :limit offset :offset "
    param["limit"] = search.limit
    param["offset"] = search.offset
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fmmtypeno'] = data[key][0]
        d1['fmmtypename'] = data[key][1]
        d1['fmemo'] = data[key][2]
        d1['fupddate'] = data[key][3]
        d1['foperator'] = data[key][4]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class MaintainTypeCreate(BaseModel):
    """保养类型新增请求参数"""
    fmmtypeno: str = Field(..., description="保养类型编号（唯一标识）")
    fmmtypename: str = Field(..., description="保养类型名称")
    foperator: str = Field(..., description="操作人")
    fupddate: str = Field(..., description="更新日期(yyyy-MM-dd HH:mm:ss)")
    fmemo: Optional[str] = Field("", description="备注")


@maintain_type_router.post("/create", summary="保养类型新增接口")
def create_maintain_type(create: MaintainTypeCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select fmmtypeno from s_ts_maintain_type where fmmtypeno= :fmmtypeno "
            data = db.execute(text(sql), {"fmmtypeno": create.fmmtypeno}).fetchall()

            if len(data) > 0:
                return BaseResponse.error(message="编号已存在")
            else:
                sql = "insert into s_ts_maintain_type(fmmtypeno,fmmtypename,fmemo,fupddate,foperator)"
                sql = sql + " values( :fmmtypeno , :fmmtypename , :fmemo , :fupddate , :foperator );"
                db.execute(text(sql), {
                    "fmmtypeno": create.fmmtypeno,
                    "fmmtypename": create.fmmtypename,
                    "fmemo": create.fmemo,
                    "fupddate": create.fupddate,
                    "foperator": create.foperator
                })
                d1 = {}
                d1["fmmtypeno"] = create.fmmtypeno
                d1["fmmtypename"] = create.fmmtypename
                d1["fmemo"] = create.fmemo
                d1["fupddate"] = create.fupddate
                d1["foperator"] = create.foperator
                return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")

@maintain_type_router.post("/update",summary="保养类修改接口")
def update_maintain_tyoe(update:MaintainTypeCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "update s_ts_maintain_type"
            sql = sql + " set fmmtypename= :fmmtypename ,fmemo= :fmemo "
            sql = sql + ",fupddate= :fupddate ,foperator= :foperator "
            sql = sql + " where fmmtypeno= :fmmtypeno "
            db.execute(text(sql), {
                "fmmtypename": update.fmmtypename,
                "fmemo": update.fmemo,
                "fupddate": update.fupddate,
                "foperator": update.foperator,
                "fmmtypeno": update.fmmtypeno
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
@maintain_type_router.post("/delete/{fmmtypeno}",summary="保养类型删除接口")
def delete_maintain_type(fmmtypeno:str=Path(description="保养类型编号"), db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select count(1) from lims.s_tc_mm_head where fmmtypeno= :fmmtypeno "
            data = db.execute(text(sql), {"fmmtypeno": fmmtypeno}).fetchall()

            if data[0][0] > 0:
                return BaseResponse.error(message="该资料在使用，不能删除")
            else:
                sql = "delete from s_ts_maintain_type where fmmtypeno= :fmmtypeno "
                db.execute(text(sql), {"fmmtypeno": fmmtypeno})
                return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
